
package com.funo.government.info.view;

import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.funo.government.info.R;
import com.funo.government.info.constant.Constant;

public class WebActivity extends BaseActivity {

    private WebView webView;

    private ProgressBar progress;

    private DownloadManager downloadManager;

    private SharedPreferences mPreference;

    private String linkUrl;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        linkUrl = getIntent().getStringExtra("link");
        webView = (WebView) findViewById(R.id.web);
        webView.setFocusable(true);
        progress = (ProgressBar) findViewById(R.id.progress);
        mPreference = PreferenceManager.getDefaultSharedPreferences(this);
        downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        WebSettings settings = webView.getSettings();
        settings.setSupportZoom(false); // 支持缩放
        settings.setBuiltInZoomControls(false); // 启用内置缩放装置
        settings.setJavaScriptEnabled(true); // 启用JS脚本
        webView.requestFocus();

        webView.setWebViewClient(new WebViewClient() {
            // 当点击链接时,希望覆盖而不是打开新窗口
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                progress.setVisibility(View.VISIBLE);
                view.loadUrl(url); // 加载新的url
                return true; // 返回true,代表事件已处理,事件流到此终止
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                progress.setVisibility(View.GONE);
                super.onPageFinished(view, url);
            }

        });
        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
                        webView.goBack(); // 后退
                        return true; // 已处理
                    }
                }
                return false;
            }
        });
        webView.setDownloadListener(new MyWebViewDownLoadListener());
        webView.loadUrl(linkUrl);

    }

    public void reload() {
        // webView.goBackOrForward(-Integer.MAX_VALUE);
        webView.loadUrl(linkUrl);
        webView.clearHistory();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String reload = getIntent().getStringExtra("reload");
        Log.i("xxx", "linkUrl:" + linkUrl + ";reload:" + reload);
    }

    private class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition,
                String mimeType, long contentLength) {

            Uri resource = Uri.parse(url);
            String filename = URLUtil.guessFileName(url, contentDisposition, mimeType);
            DownloadManager.Request request = new DownloadManager.Request(resource);
            request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
            request.setAllowedOverRoaming(false);
            request.setMimeType(mimeType);
            if (Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
                request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            } else {
                // 在通知栏中显示
                request.setShowRunningNotification(true);
            }
            request.setVisibleInDownloadsUi(true);
            // sdcard的目录下的download文件夹
            request.setDestinationInExternalPublicDir("/longyan_download/", filename);
            request.setTitle(filename + " downloading");
            long id = downloadManager.enqueue(request);
            String ids = mPreference.getString(Constant.PRE_KEY_DOWNLOAD_IDS, "");
            mPreference
                    .edit()
                    .putString(Constant.PRE_KEY_DOWNLOAD_IDS,
                            ids + (TextUtils.isEmpty(ids) ? "" : ",") + id).commit();
        }

    }

}
